//
//  SystemMessageDetailViewController.swift
//  甜言蜜语
//
//  Created by 王剑伟 on 16/6/28.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import SVProgressHUD
class SystemMessageDetailViewController: UIViewController, DetailShareViewDelegate, UIActionSheetDelegate,UIWebViewDelegate {

   
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var collectionBtn: UIButton!
    @IBOutlet weak var shareBtn: UIButton!
    var id: String!
    var isshoucang: Bool?
    var shareView: DetailShareView?
    var actionSheet: UIActionSheet? = nil
    var fontSize: Int?
    var model: NewsDetailModel? {
        didSet {
            self.loadNewsDetail()
            self.collectionImg()
            self.initRightItem()
        }
    }
    var msg: regiestInfo?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "系统消息详情"
        //字体大小
        let str = ApplicationDelegate.fontSize()
        self.fontSize  =  Int( (str as NSString).intValue)
        self.webView.delegate = self
        publicMethod.setHUDStyle()
        self.getSystemDetailData()
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.hidden = true
    }
    
    func collectionImg(){
        if self.model?.isshoucang == true{
            self.collectionBtn.setImage(UIImage(named: "collection_selected"), forState: UIControlState.Normal)
        }else{
            self.collectionBtn.setImage(UIImage(named: "collection"), forState: UIControlState.Normal)
        }
        
    }
    func initRightItem(){
        let rightBtn = UIButton(frame: CGRectMake(0, 0, 25, 25))
        rightBtn.setBackgroundImage(UIImage(named: "right_item")!, forState: UIControlState.Normal)
        rightBtn.addTarget(self, action: #selector(self.rigthAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let rightItem = UIBarButtonItem(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
 
    }
    func rigthAction(sender: UIButton){
        sender.selected = !sender.selected
        if sender.selected{
            shareView = DetailShareView.init(frame: kScreen_frame)
            shareView?.delegate = self
            self.view.addSubview(shareView!)
        }else{
            shareView?.closeBtnClick()
        }
        
    }
    //MARK:DetailShareViewDelegate
    func wechatCircle(){
        if publicMethod.isWechat(){
            let shareParames = NSMutableDictionary()
            let url =  String(format: "%@message/fenxiang/\(id!)",BaseUrl)
            shareParames.SSDKSetupShareParamsByText("",
                                                    images : UIImage(named: "ShareImg.png"),
                                                    url : NSURL(string: url),
                                                    title : self.model?.title,
                                                    type : SSDKContentType.Auto)
            
            
            //2.显示分享编辑页面
            ShareSDK.showShareEditor(SSDKPlatformType.SubTypeWechatTimeline, otherPlatformTypes: nil, shareParams: shareParames) { (state :SSDKResponseState, platformType : SSDKPlatformType , userData: [NSObject : AnyObject]!, contentEntity : SSDKContentEntity!, error : NSError!, end) -> Void in
                
                switch state{
                    
                case SSDKResponseState.Success: self.showAlert("分享成功")
                case SSDKResponseState.Fail:    self.showAlert("分享失败")
                case SSDKResponseState.Cancel:  self.showAlert("分享取消")
                    
                default:
                    break
                }
            }

        }else{
            self.showAlert("您还没有安装微信")
        }
        
    }
    func wechatFriend(){
        if publicMethod.isWechat(){
            let shareParames = NSMutableDictionary()
            let url =  String(format: "%@message/fenxiang/\(id!)",BaseUrl)
            shareParames.SSDKSetupShareParamsByText("",
                images : UIImage(named: "ShareImg.png"),
                url : NSURL(string: url),
                title : self.model?.title,
                type : SSDKContentType.Auto)
            
            
            //2.显示分享编辑页面
            ShareSDK.showShareEditor(SSDKPlatformType.SubTypeWechatSession, otherPlatformTypes: nil, shareParams: shareParames) { (state :SSDKResponseState, platformType : SSDKPlatformType , userData: [NSObject : AnyObject]!, contentEntity : SSDKContentEntity!, error : NSError!, end) -> Void in
                
                switch state{
                    
                case SSDKResponseState.Success: self.showAlert("分享成功")
                case SSDKResponseState.Fail:    self.showAlert("分享失败")
                case SSDKResponseState.Cancel:  self.showAlert("分享取消")
                    
                default:
                    break
                }
            }

        }else{
            self.showAlert("您还没有安装微信")
        }
        
        
    }
    func qqFriend(){
        if publicMethod.isQQ(){
            let shareParames = NSMutableDictionary()
            let url =  String(format: "%@message/fenxiang/\(id!)",BaseUrl)
            shareParames.SSDKSetupShareParamsByText("",
                                                    images : UIImage(named: "ShareImg.png"),
                                                    url : NSURL(string: url),
                                                    title : self.model?.title,
                                                    type : SSDKContentType.Auto)
            
            
            //2.显示分享编辑页面
            ShareSDK.showShareEditor(SSDKPlatformType.SubTypeQQFriend, otherPlatformTypes: nil, shareParams: shareParames) { (state :SSDKResponseState, platformType : SSDKPlatformType , userData: [NSObject : AnyObject]!, contentEntity : SSDKContentEntity!, error : NSError!, end) -> Void in
                
                switch state{
                    
                case SSDKResponseState.Success: self.showAlert("分享成功")
                case SSDKResponseState.Fail:    self.showAlert("分享失败")
                case SSDKResponseState.Cancel:  self.showAlert("分享取消")
                    
                default:
                    break
                }
            }

        }else{
            self.showAlert("你还没有安装QQ")
        }
        
        
    }
    func qqZone(){
        if publicMethod.isQQ(){
            let shareParames = NSMutableDictionary()
            let url =  String(format: "%@message/fenxiang/\(id!)",BaseUrl)
            shareParames.SSDKSetupShareParamsByText("",
                                                    images : UIImage(named: "ShareImg.png"),
                                                    url : NSURL(string: url),
                                                    title : self.model?.title,
                                                    type : SSDKContentType.Auto)
            
            
            //2.显示分享编辑页面
            ShareSDK.showShareEditor(SSDKPlatformType.SubTypeQZone, otherPlatformTypes: nil, shareParams: shareParames) { (state :SSDKResponseState, platformType : SSDKPlatformType , userData: [NSObject : AnyObject]!, contentEntity : SSDKContentEntity!, error : NSError!, end) -> Void in
                
                switch state{
                    
                case SSDKResponseState.Success: self.showAlert("分享成功")
                case SSDKResponseState.Fail:    self.showAlert("分享失败")
                case SSDKResponseState.Cancel:  self.showAlert("分享取消")
                    
                default:
                    break
                }
            }

        }else{
            self.showAlert("你还没有安装QQ")
        }
        
        
    }
    func weibo(){
        let shareParames = NSMutableDictionary()
        let url =  String(format: "%@message/fenxiang/\(id!)",BaseUrl)
        shareParames.SSDKSetupShareParamsByText(url,
                                                images : UIImage(named: "ShareImg.png"),
                                                url : NSURL(string:url),
                                                title : self.model?.title,
                                                type : SSDKContentType.Auto)
        //2.显示分享编辑页面
        ShareSDK.showShareEditor(SSDKPlatformType.TypeSinaWeibo, otherPlatformTypes: nil, shareParams: shareParames) { (state :SSDKResponseState, platformType : SSDKPlatformType , userData: [NSObject : AnyObject]!, contentEntity : SSDKContentEntity!, error : NSError!, end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: self.showAlert("分享成功")
            case SSDKResponseState.Fail:    self.showAlert("分享失败")
            case SSDKResponseState.Cancel:  self.showAlert("分享取消")
                
            default:
                break
            }
        }
        
        
    }
    func foneSize(){
        if (actionSheet == nil) {
            self.actionSheet = UIActionSheet(title: "选择字体大小",delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles:"特大", "大", "中","小")
        }
        self.actionSheet!.showInView(self.view!)

    }
    func report(){
        let sb = UIStoryboard.init(name: "NewsList", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("ReportVC") as! ReportVC
        vc.id = String(self.model!.docid)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func collection(){
        if ApplicationDelegate.isLogin(){
            if self.model?.isshoucang == true{
                self.isshoucang = false
            }else{
                self.isshoucang = true
            }
            
            DataTool.collectionNews((id)!,isshoucang: self.isshoucang!, type:"产品推荐", completionHandler: { (newsData)
                in
                guard let newsDetailData = newsData else {
                    return
                }
                self.msg = newsDetailData
                self.getSystemDetailData()
                
                SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
                
            })

        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    //MARK:actionSheetDelegate
    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            //大
            print("特大")
            
            NSUserDefaults.standardUserDefaults().setObject("20" , forKey:"fontSizeDefaut")
            
        }else if buttonIndex == 2 {
            //大
            print("大")
            
            NSUserDefaults.standardUserDefaults().setObject("18" , forKey:"fontSizeDefaut")
            
        }else if buttonIndex == 3{
            //中
            print("中")
            
            NSUserDefaults.standardUserDefaults().setObject("16" , forKey:"fontSizeDefaut")
            
        }else{
            //小
            print("小")
            
            NSUserDefaults.standardUserDefaults().setObject("14" , forKey:"fontSizeDefaut")
        }
        
    }

    //MARK:showAlert
    func showAlert(message: String){
        let alertView = UIAlertView(title: "", message: message, delegate: nil, cancelButtonTitle: "确定" )
        
        alertView.show()
    }
    //MARK:networking
    //下拉刷新
    func getSystemDetailData(){
        DataTool.loadSystemDetailData(String(id!), completionHandler: { (newsData) in
            guard let newsDetailData = newsData else {
                return
            }
            self.model = newsDetailData
           
        })

    }
       //MARK: webViewLoadInfo
    /**
     这里用来显示被点击的那一张图片
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let str = request.URL?.absoluteString
        if let temp = str?.componentsSeparatedByString("=") where temp.count > 1{
            DetailPictureView.showAtWindow(self.model!, index: Int(temp.last!)!)
        }
        
        return true
    }
    
  

      /**
     加载描述界面
     */
    func loadNewsDetail() {
        assert(self.model != nil)
        let css = NSBundle.mainBundle().URLForResource("Details.css", withExtension: nil)!
        
        var html = "<html>"
        
        html += "<head>"
        html += "<link rel=\"stylesheet\" href="
        html += "\"\(css)\""
        html += ">"
        html += "</head>"
        
        html += self.getBody()
        html += "</html>"
        
        self.webView.loadHTMLString(html, baseURL: nil)
        
    }
    
    /**
     被loadNewsDetail方法调用，用来拼接<body>的内容
     */
    func getBody() -> String{
        
        var body = "<body>"
        
        body += "<div class=\"title\">"
        body += self.model!.title
        body += "</div>"
        body += "<table width='400' border='0' cellspacing='0' cellpadding='0'>"
        body += "<tbody>"
        body += "<tr>"
        body += "<td  width='50' rowspan='2'><img src='\(self.model!.timg)' width='50' height='50' alt=''/></td>"
        body += "<td height='30' style='padding-left:10px'>"
        body += "\(self.model!.contributor)"
        body += "</td>"
        body += "</tr>"
        body += "<tr>"
        body += "<td height='30' style='padding-left:10px;font-size:12px;'><span style='padding:2px; border:1px solid #000000;border-radius:3px;'>"
        body += "\(self.model!.tags)"
        body += "</span>"
        body += "\(self.model!.ptime)"
        body += "</td>"
        body += "</tr>"
        body += "</tbody>"
        body += "</table>"
        
        body += self.model!.body
        
        for (index, detailImageModel) in self.model!.img.enumerate() {
            var imgTag = "<div class=\"image\">"
            
            imgTag += "<img id=\"\(index)\" "
            //用 * 符号切割字符串，"haha*hehe*xixi" ==>  "haha" "hehe" "xixi"
            let pixel = detailImageModel.pixel.componentsSeparatedByString("*")
            var width = Float(pixel.first!) ?? 0
            var height = Float(pixel.last!) ?? 0
            
            let maxWidth = Float(self.view.bounds.width * 0.95)
            if width > maxWidth {
                height =  height *  maxWidth / width
                width = maxWidth
            }
            
            // 这里是添加图片点击事件
            imgTag += "onload="
            imgTag += "\""
            imgTag += "this.onclick = function() {  window.location.href = 'sx:index=' +this.id;};"
            imgTag += "\""
            
            imgTag += "width=\(width) "
            imgTag += "height=\(height) "
            imgTag += "src=\(detailImageModel.src)>"
            
            imgTag += "<div class=\"imageDetail\">"
            imgTag += "\(detailImageModel.alt)"
            imgTag += "</div>"
            
            
            imgTag += "</div>"
            
            // 替换位置
            body = body.stringByReplacingOccurrencesOfString(detailImageModel.ref, withString: imgTag)
        }
        
        body += "</body>"
        
        return body
    }
    
    
    @IBAction func onCollectionClick(sender: UIButton) {
        if ApplicationDelegate.isLogin(){
            if self.model?.isshoucang == true{
                self.isshoucang = false
            }else{
                self.isshoucang = true
            }
            DataTool.collectionNews((id)!,isshoucang: self.isshoucang!, type:"产品推荐", completionHandler: { (newsData)
                in
                guard let newsDetailData = newsData else {
                    return
                }
                self.msg = newsDetailData
                self.getSystemDetailData()
                
                SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
                
            })
        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
    
     }
    
    
    
    @IBAction func onShareClick(sender: UIButton) {
        
        self.transBtnClicked()
    }
    func transBtnClicked(){
        
        let shareParames = NSMutableDictionary()
        let url = String(format: "%@message/fenxiang/\(id!)",BaseUrl)
        shareParames.SSDKSetupShareParamsByText("",
                                                images : UIImage(named: "ShareImg.png"),
                                                url : NSURL(string:url),
                                                title : self.model?.title,
                                                type : SSDKContentType.Auto)
        
        
        //2.进行分享
        SSUIShareActionSheetStyle.setShareActionSheetStyle(ShareActionSheetStyle.Simple)
        
        ShareSDK.showShareActionSheet(self.view, items: nil  , shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("分享成功")
            case SSDKResponseState.Fail:    print("分享失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  print("分享取消")
                
            default:
                break
            }
        }
    }


    
}
